// 防抖
export const debounce = (fn, delay) => {
  let timer = null
  return function () {
    let context = this
    let args = arguments
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(context, args)
    }, delay)
  }
}

export const replaceAll = (str, find, replace) => {
  return str.replace(new RegExp(find, 'g'), replace)
}
//  生成30个不同颜色
export const generateColors = () => {
  const colors = []
  for (let i = 0; i < 30; i++) {
    colors.push(`#${Math.floor(Math.random() * 16777215).toString(16)}`)
  }
  return colors
}
// 导出会议列表头像底色
export const colors = [
  '#5fa4e9',
  '#0bf561',
  '#61b85b',
  '#ded152',
  '#4297fa',
  '#c681e8',
  '#52cf96',
  '#028fd1',
  '#fb75e1',
  '#70b19b',
  '#5dddeb',
  '#1371e7',
  '#932483',
  '#d85875',
  '#59cc84',
  '#84220f',
  '#d956b5',
  '#0b055e',
  '#f2ef0b',
  '#68dece',
  '#c69e0d',
  '#335557',
  '#df6b65',
  '#29aa8a',
  '#f729b4',
  '#d7a631',
  '#a2c8e5',
  '#3073df',
  '#8855e1',
  '#a1bfd2',
]
// 截取首个字母 若是数字全部返回 其他jie取第一个
export const convertString = (str) => {
  if (/^[0-9]+$/.test(str)) {
    return str
  } else if (/^[a-zA-Z]+$/.test(str)) {
    return str.charAt(0)
  } else {
    return str.charAt(0)
  }
}
/**
 * 将树形结构拍平
 * @param {*} tree
 * @returns
 */
export const flatTree = (tree) => {
  return tree.reduce((acc, node) => {
    acc.push(node)
    if (node.children) {
      acc.push(...flatTree(node.children))
    }
    return acc
  }, [])
}
/** 添加标签 */
export function addLabel(tree, parentLabel = '') {
  tree.forEach((item) => {
    item.path = parentLabel + item.label
    if (item.children) {
      addLabel(item.children, parentLabel + item.label + '/')
    }
  })
}

/**
 * 树形结构
 */
export const generateTree = (data) => {
  let map = {}
  let arr = []
  data.forEach((item) => {
    item.label = item.id
    map[item.id] = item
  })
  data.forEach((item) => {
    if (item.parent_id) {
      if (map[item.parent_id]) {
        if (!map[item.parent_id].children) {
          map[item.parent_id].children = []
        }
        map[item.parent_id].children.push(item)
      }
    } else {
      arr.push({
        ...item,
      })
    }
  })
  return arr
}
export function addLabels(tree, parentLabel = '') {
  tree.forEach((item) => {
    item.path = parentLabel + item.id
    if (item.children) {
      addLabels(item.children, parentLabel + item.id + '/')
    }
  })
}

export function downloadFile(data, fileName) {
  let link = document.createElement('a')
  link.href = (URL || webkitURL).createObjectURL(data)
  link.setAttribute('download', fileName)
  link.click()
  link.remove()
}
// 替换html img 标签设置大小
export function replaceImg(innerHTML, width, height) {
  const imgTags = innerHTML.match(/<img[^>]*>/g)
  if (imgTags) {
    imgTags.forEach((tag) => {
      // 使用DOMParser来解析标签，并设置宽度和高度
      const parser = new DOMParser()
      const doc = parser.parseFromString(tag, 'text/html')
      const img = doc.querySelector('img')
      if (img) {
        img.setAttribute('width', width) // 设置宽度
        img.setAttribute('height', height) // 设置高度
        tag = img.outerHTML // 获取更新后的HTML
      }
      // 替换原始的<img>标签
      innerHTML = innerHTML.replace(/<img[^>]*>/g, tag)
      // innerHTML = innerHTML.replace(new RegExp(tag, 'g'), tag)
    })
  }
  return innerHTML
}

// 去除html img标签
export function removeImgFromHtml(html) {
  // 使用正则表达式替换 img 标签
  html = html.replace(/<img[^>]*>/g, '')

  // 将 HTML 字符串解析为 DOM 元素
  const div = document.createElement('div')
  div.innerHTML = html

  // 遍历 DOM 元素，删除带有 img 标签的子元素
  const children: any = div.childNodes
  for (let i = 0; i < children.length; i++) {
    if (children[i].nodeType === 1 && children[i].tagName === 'IMG') {
      children[i].parentNode.removeChild(children[i])
    }
  }

  // 返回处理后的 HTML 字符串
  return div.innerHTML
}

// 格式化时间为多少分钟 多少小时 多少天 多少年之前
export const formatTime = (time) => {
  const now = new Date().getTime()
  const diff = now - time
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  const month = 30 * day
  const year = 12 * month
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return Math.floor(diff / minute) + '分钟前'
  } else if (diff < day) {
    return Math.floor(diff / hour) + '小时前'
  } else if (diff < month) {
    return Math.floor(diff / day) + '天前'
  } else if (diff < year) {
    return Math.floor(diff / month) + '个月前'
  } else {
    return Math.floor(diff / year) + '年前'
  }
}
/**
 * hash 转为rgba
 * @param {*} color
 * @param {*} alpha
 * @returns
 */
export const colorToRgba = (color: string, alpha: number = 0.4) => {
  if (color.startsWith('rgba')) {
    return color
  }
  if (color.startsWith('rgb')) {
    return color.replace('rgb', 'rgba').replace(')', `,${alpha}`)
  }
  if (color.startsWith('#')) {
    color = color.replace('#', '')
  }
  if (color.length === 3) {
    color = color
      .split('')
      .map((char) => char + char)
      .join('')
  }
  const first: string = color.slice(0, 2)
  const second: string = color.slice(2, 4)
  const third: string = color.slice(4, 6)
  return `rgba(${parseInt(first, 16)}, ${parseInt(second, 16)}, ${parseInt(
    third,
    16,
  )}, ${alpha})`
}

export function millisecondsToTime(ms: number) {
  const totalSeconds = Math.floor(ms / 1000)
  const hours = Math.floor(totalSeconds / 3600)
  const minutes = Math.floor((totalSeconds % 3600) / 60)
  const seconds = totalSeconds % 60
  let arr = [
    String(hours).padStart(2, '0'),
    String(minutes).padStart(2, '0'),
    String(seconds).padStart(2, '0'),
  ]
  if (arr[0] === '00') {
    arr.splice(0, 1)
  }
  return arr.join(':')
}

/**
 * 树形结构添加id
 * @param node 节点
 * @param parentLevel 父级层级
 */
export function addIdsToParent(node, parentLevel) {
  if (!node.childIds) {
    node.childIds = []
  }
  node.childIds.push(node.id)
  node.level = parentLevel ? ++parentLevel : 1
  node.deepLevel = node.level ? node.level : 1
  if (node.children && node.children.length > 0) {
    node.children.forEach((child) => {
      addIdsToParent(child, node.level)
      node.childIds.push(...child.childIds)
      node.deepLevel = Math.max(node.deepLevel, child.deepLevel)
    })
  }
}
/**
 * 导出为txt
 * @param content 内容
 */
export const exportToTxt = (content, filename) => {
  const blob = new Blob([content], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename + '.txt'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}
/**
 *  导出为md
 * @param content 内容
 */
export const exportToMd = (content) => {
  const blob = new Blob([content], { type: 'text/markdown' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'file.md'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

/**
 * 下载视频
 * @param url 视频地址
 * @param fileName  文件名
 */
export const downloadVideo = (url, fileName = 'video.mp4') => {
  const a = document.createElement('a')
  a.href = url
  a.download = fileName
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

export function removeFieldFromTree(data, fieldName) {
  if (!Array.isArray(data)) {
    return data
  }
  return data.map((node) => {
    const newNode = { ...node }
    delete newNode[fieldName]
    if (newNode.children) {
      newNode.children = removeFieldFromTree(newNode.children, fieldName)
    }

    return newNode
  })
}